#include "deviceIdManager.h"

std::string getHardwareAddress()
{
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(popen("ifconfig", "r"), pclose);

    if (!pipe)
    {
        std::cerr << "popen() failed!" << std::endl;
        return "";
    }

    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
    {
        result += buffer.data();
    }

    // Parse the output to find the HWaddr
    std::string::size_type pos = result.find("HWaddr");
    if (pos != std::string::npos)
    {
        // Extract the HWaddr
        pos += 6; // Move past "HWaddr "
        std::string hwaddr;
        while (pos < result.size() && result[pos] != '\n')
        {
            hwaddr += result[pos++];
        }
        return hwaddr; // Return the hardware address
    }
    return ""; // Return empty if HWaddr not found
}

std::string findDeviceCode()
{
    std::ifstream file("/oem/usr/bin/mac_bsa.txt");
    std::string line;
    std::string localHwAddr = getHardwareAddress();
    printf("HardwareAddress is %s\n", localHwAddr.c_str());

    if (localHwAddr.empty())
    {
        std::cerr << "Failed to get local hardware address." << std::endl;
        return "";
    }

    while (std::getline(file, line))
    {
        std::istringstream iss(line);
        std::string hwaddr, deviceCode;

        // Read the hardware address and device code from the file
        if (iss >> hwaddr >> deviceCode)
        {
            // 标准化 MAC 地址
            std::string normalizedMac1 = normalizeMacAddress(localHwAddr);
            std::string normalizedMac2 = normalizeMacAddress(hwaddr);

            printf("Comparing: '%s' vs '%s'\n", normalizedMac1.c_str(), normalizedMac2.c_str());
            /*
            printf("hwaddr: [%s] (len=%zu, hex: ", normalizedMac1.c_str(), normalizedMac1.length());
            for (char c : normalizedMac1)
                printf("%02x ", static_cast<unsigned char>(c));
            printf(")\n");

            printf("txtaddr: [%s] (len=%zu, hex: ", normalizedMac2.c_str(), normalizedMac2.length());
            for (char c : normalizedMac2)
                printf("%02x ", static_cast<unsigned char>(c));
            printf(")\n");*/

            // Compare the addresses (ignore case)

            // int res = strcmp(normalizedMac1.c_str(), normalizedMac2.c_str());
            // int res = bcmp(normalizedMac1.c_str(), normalizedMac2.c_str(), sizeof(normalizedMac1));
            // int res = normalizedMac1.compare(normalizedMac2);
            int res = normalizedMac1 == normalizedMac2;
            printf("hwaddr is %s, txtaddr is %s, result is %d\n", hwaddr.c_str(), deviceCode.c_str(), res);
            if (res)
            {
                return deviceCode; // Return the matching device code
            }
            // else
            // {
            //     deviceCode="99";
            //     return deviceCode;
            // }
        }
    }

    return ""; // Return empty if no match found
}
std::string normalizeMacAddress(const std::string &mac)
{
    std::string normalized;
    for (char c : mac)
    {
        if (std::isxdigit(c))
        { // 只保留十六进制字符（0-9, a-f, A-F）
            normalized += std::tolower(c);
        }
    }
    return normalized;
}